<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="地图选址"
      width="800px"
      :close-on-click-modal="true"
    >
      <div class="box">
        <div class="info">
          <!-- <div class="input-item">
            <div class="input-item-prepend">
              <span class="input-item-text" style="width:100px">请输入关键字</span>
            </div>
            <el-input
              v-model="keywords"
              style=""
              placeholder="请输入关键字"
            >
              <template #append>
                <el-button type="primary" :icon="Search"></el-button>
              </template>
            </el-input>
          </div> -->
          <el-input
              v-model="keywords"
              style=""
              placeholder="请输入关键字"
            >
            <template #append>
              <el-button type="primary" :icon="Search" @click="onSearch"></el-button>
            </template>
          </el-input>
        </div>
        <div id="container" style="width:750px; height:600px"></div>
        
      </div>
      <div class="bottom">
        <el-button @click="() => {dialogVisible = false}">取消</el-button>
        <el-button type="primary" @click="onRight">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import AMap from '@amap/amap-jsapi-loader'
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue'


const dialogVisible = ref(false);
// 父组件修改子组件数据
defineExpose({
  dialogVisible(res: boolean){
    dialogVisible.value = res;
    nextTick(()=>{
      init()
    })
  },
  keywords(res: string) {
     keywords.value = res
  }
})
const emit = defineEmits(['save'])
onMounted(()=>{
  console.log('onMounted');
})

// let map: any = null;
let markerObj:any = null
const keywords = ref('')
const AMapCopy: any = ref({})
const map:any = ref({})
const placeSearch:any = ref({})
let adcode: any = null
const onSearch = () => {
  console.log('search');
  console.log(keywords.value);
  if (keywords.value == '') {
    ElMessage.error('请输入关键字')
    return false
  } 
  console.log(placeSearch.value)
  // init()
  select()
  
}

const onRight = ()=> {
  if (markerObj == null) {
    ElMessage.error('请先搜索获取地址');
    return false
  }
  console.log(markerObj)
  emit('save', markerObj)
  dialogVisible.value = false;
}

const init = () => {
  AMap.load({
   key: "14162c04f12bcb7a4032b2b37bddea55", // 申请好的Web端开发者Key，首次调用 load 时必填
   version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
   plugins: ["AMap.Scale", 'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.PlaceSearch'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
 }).then((AMap) => {
    map.value = new AMap.Map("container", {
      // 设置地图容器id
      viewMode: "3D", // 是否为3D地图模式
      zoom: 11, // 初始化地图级别
    });

    //插件使用
    AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位，默认：true
        timeout: 1000, // 设置定位超时时间，默认：无穷大
        offset: [10, 20],  // 定位按钮的停靠位置的偏移量
        zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        position: 'RB', //  定位按钮的排放位置,  RB表示右下
      })
      map.value.addControl(geolocation);
      geolocation.getCurrentPosition(
        function(status: string,result: any){
            if(status=='complete'){
              onComplete(result)
            }else{
              // onError(result)
              geolocation.getCityInfo(async (status: string, result:any) => {
                if (status == "complete") {
                  console.log("城市定位", result)
                  adcode = result.citycode
                  const longitude = (result.position[0]).toFixed(1);//经度
                  const latitude = (result.position[1]).toFixed(1);
                  console.log("经纬度:", longitude, latitude);
                  let position = new AMap.LngLat(longitude, latitude);
                  console.log(position, 'position');
                }
              })
            }
      })
    })
    AMapCopy.value = AMap
    placeSearch.value = new AMap.PlaceSearch({
        map: map
    });

    return false
    AMap.plugin(['AMap.PlaceSearch'], function(){
        // POI的插件
        var placeSearch = new AMap.PlaceSearch({
            map: map
        });  //构造地点查询类
        console.log(adcode)
        console.log(keywords.value)
        // 区域code和搜索关键字
        if (adcode && keywords.value) {
          select()
        }
        function select(){
          placeSearch.setCity(adcode);
          placeSearch.search(keywords.value, function(status: any, result: any) {
              console.log(status)
              console.log(result)
              var infoWindow = new AMap.InfoWindow({});
              function createContent(poi: { name: string; address: string; tel: string; }) {  //信息窗体内容
                  // var s = [];
                  // s.push('<div class="amap-lib-infowindow-title">1.'+poi.name+'</div><div class="amap-lib-infowindow-content-wrap">'+"地址：" + poi.address);
                  // s.push("电话：" + poi.tel);
                  // s.push('<div>');
                  // return s.join("<br>");
                  return `<div class="amap-lib-infowindow-title">1.${poi.name}</div>
                  <div class="amap-lib-infowindow-content">
                    <div class="amap-lib-infowindow-content-wrap">
                      <div>地址：${poi.address}</div>
                      ${poi.tel?`<div>电话：${poi.tel}</div>`:''}
                    </div>
                  </div>
                  `
              }
              console.log(result.poiList)
              console.log(result.poiList.pois)
              infoWindow.setContent(createContent(result.poiList.pois[0]));
              infoWindow.open(map, result.poiList.pois[0].location);
              markerObj = result.poiList.pois[0]
              map.setZoomAndCenter(18, [result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat]);
              // infoWindow.open(map, [result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat]);
              
          });  //关键字查询查询
          // 为marker注册点击事件
          placeSearch.on('markerClick', function (e: any) {
            // 根据点击marker进行下一步
            console.log(e)
            markerObj = e.data
          });
        }
    })

  }).catch((e: any) => {
    console.log(e);
  });
}

function onComplete(result: any) {
  ElMessage('定位成功')
  console.log(result)
}

function select(){
  placeSearch.value.setCity(adcode);
  placeSearch.value.search(keywords.value, function(status: any, result: any) {
      console.log(status)
      console.log(result)
      var infoWindow = new AMapCopy.value.InfoWindow({});
      function createContent(poi: { name: string; address: string; tel: string; }) {  //信息窗体内容
          // var s = [];
          // s.push('<div class="amap-lib-infowindow-title">1.'+poi.name+'</div><div class="amap-lib-infowindow-content-wrap">'+"地址：" + poi.address);
          // s.push("电话：" + poi.tel);
          // s.push('<div>');
          // return s.join("<br>");
          return `<div class="amap-lib-infowindow-title">1.${poi.name}</div>
          <div class="amap-lib-infowindow-content">
            <div class="amap-lib-infowindow-content-wrap">
              <div>地址：${poi.address}</div>
              ${poi.tel?`<div>电话：${poi.tel}</div>`:''}
            </div>
          </div>
          `
      }
      console.log(result.poiList)
      console.log(result.poiList.pois)
      infoWindow.setContent(createContent(result.poiList.pois[0]));
      infoWindow.open(map.value, result.poiList.pois[0].location);

      markerObj = result.poiList.pois[0]
      map.value.setZoomAndCenter(16, [result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat]);


      // infoWindow.open(map, [result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat]);
      
  });  //关键字查询查询
  // 为marker注册点击事件
  placeSearch.value.on('markerClick', function (e: any) {
    // 根据点击marker进行下一步
    console.log(e)
    markerObj = e.data
  });
}

</script> 

<style lang="scss" scoped>
.box{
  position: relative;
}
.info {
  padding: 6px;
  margin-bottom: 20px;
  border-radius: .25px;
  position: absolute;
  top: 30px;
  right: 30px;
  z-index: 2000;
  background-color: white;
  width: 300px;
  min-width: 200px;
  border-width: 0;
  // box-shadow: 0 2px 6px 0 rgba(240, 131, 0, .5);
  .input-item {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    width: 100%;
    height: 40px;
    border: 1px solid #CCC;
    border-radius: 10px;
    overflow: hidden;
    .input-item-prepend {
      margin-right: -1px;
    }
    .input-item-prepend {
      width: 35%;
      font-size: 13px;
      // border-right: 1px solid #CCC;
      height: 100%;
      display: flex;
      align-items: center;
      background-color: #e9ecef;
      // border: 1px solid #ced4da;
      span {
        text-align: center;
      }
    }
    input {
      width: 60%;
      background: #fff;
      padding: 6px 10px;
      margin-left: 10px;
      border: none;
    }
  }
}
#tipinput:focus-visible{
  outline: none;
}
.bottom{
  display: flex;
  justify-content: center;
  padding-top: 20px;
}
</style>
